package com.jack.leetcode.每日一题;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/***
 * @author zhangjie
 * @date 2020/4/14 22:25
 */
public class 两数相加2 {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(7);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(4);
        l1.next.next.next = new ListNode(3);
        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);
        ListNode result = addTwoNumbers(l1,l2);
        while(result!=null){
            System.out.println(result.val);
            result = result.next;
        }
    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = null;
        Stack<Integer> x = new Stack<>();
        Stack<Integer> y = new Stack<>();
        while(l1!=null){
            x.push(l1.val);
            l1 = l1.next;
        }
        while(l2!=null){
            y.push(l2.val);
            l2 = l2.next;
        }
        int carry = 0;
        while(!x.empty()||!y.empty()||carry>0){
            int sum = carry;
            sum+=x.empty()?0:x.pop();
            sum+=y.empty()?0:y.pop();
            ListNode tmp = new ListNode(sum%10);
            tmp.next = result;
            result = tmp;
            carry = sum/10;
        }
        return result;
    }

    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
}
